package com.cyh.core.login.handler;

import com.cyh.core.framework.annotation.PassToken;
import com.cyh.core.framework.annotation.RoleToken;
import com.cyh.core.framework.annotation.UserLoginToken;
import com.cyh.core.framework.domain.dto.ResultDTO;
import com.cyh.core.login.entity.Role;
import com.cyh.core.login.entity.User;
import com.cyh.core.login.service.user.IUserService;
import com.cyh.core.framework.common.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class AuthenticationInterceptor implements HandlerInterceptor {

    @Value("${server.servlet.context-path}")
    String contextPath;

    @Value("${cyh.constant.admin.code}")
    int adminCode;

    @Value("${cyh.permit-url.dev-urls}")
    String permitUrl;

    private static List<String> permitUrlList;

    @Autowired
    IUserService iUserService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {

        if(permitUrlList==null && permitUrl!="" && permitUrl!=null){
            permitUrlList=new ArrayList<>();
            String[] urls=permitUrl.split(",");
            for (String url:urls
                 ) {
                permitUrlList.add(url.replace(" ",""));
            }
        }

        String Aurl=httpServletRequest.getContextPath() +httpServletRequest.getServletPath();

        if(ispermitUrl(Aurl)){
            return true;
        }

        System.out.println(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())+"  Url:"+httpServletRequest.getScheme()+"://"+httpServletRequest.getServerName()
        +":"+httpServletRequest.getServerPort()+Aurl+"?"+httpServletRequest.getQueryString()
                );

        httpServletResponse.setHeader("Content-type", "application/json;charset=UTF-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        Cookie []cookies= httpServletRequest.getCookies();
        String token =null;
        ResultDTO resultDTO=ResultDTO.Failure(400);
        if(cookies!=null) {
            for (Cookie coo : cookies) {
                if (coo.getName().equals("token")) {
                    token = coo.getValue();
                    break;
                }
            }
        }
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();


        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(RoleToken.class)) {
            RoleToken roleToken = method.getAnnotation(RoleToken.class);
            int [] rids=roleToken.Roleid();
            if(rids==null || rids.length==0){
                System.out.println("访问无需权限...");
            }else {
                List<Integer> list = Arrays.stream(rids).boxed().collect(Collectors.toList());
                boolean isok = check(token, resultDTO, httpServletResponse);
                if (isok) {
                    User user = iUserService.getCurrentUser();
                    if (user.getTempObject() instanceof Role) {
                        Role role = (Role) user.getTempObject();
                        if (role.getRid().intValue() == adminCode) return true;
                        if (!list.contains(role.getRid())) {
                            PrintWriter out = httpServletResponse.getWriter();
                            resultDTO.setMsg("权限不足");
                            resultDTO.setStatus(403);
                            out.println(resultDTO);
                            out.flush();
                            out.close();
                            return false;
                        }
                    } else {
                        PrintWriter out = httpServletResponse.getWriter();
                        resultDTO.setMsg("未知错误");
                        resultDTO.setStatus(500);
                        out.println(resultDTO);
                        out.flush();
                        out.close();
                        return false;
                    }
                } else {
                    PrintWriter out = httpServletResponse.getWriter();
                    resultDTO.setMsg("未知错误");
                    resultDTO.setStatus(500);
                    out.println(resultDTO);
                    out.flush();
                    out.close();
                    return false;
                }
                return true;
            }
            return check(token, resultDTO, httpServletResponse);
        }

        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                return check(token,resultDTO,httpServletResponse);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }

    private boolean check(String token,ResultDTO resultDTO,HttpServletResponse httpServletResponse) throws IOException {
        if (token == null) {
            PrintWriter out=httpServletResponse.getWriter();
            resultDTO.setMsg("无token，请重新登录");
            out.println(resultDTO);
            out.flush();
            out.close();
            return false;
            //throw new RuntimeException("无token，请重新登录");
        }
        String userId= JWTUtil.GetIdFromToken(token);
        if(userId==null){
            PrintWriter out=httpServletResponse.getWriter();
            resultDTO.setMsg("token解析失败");
            out.println(resultDTO);
            out.flush();
            out.close();
            return false;
        }
        User user = iUserService.getCurrentUser();

        if (user == null) {
            PrintWriter out=httpServletResponse.getWriter();
            resultDTO.setMsg("用户不存在，请重新登录");
            out.println(resultDTO);
            out.flush();
            out.close();
            return false;
            //throw new RuntimeException("用户不存在，请重新登录");
        }
        // 验证 token
        if(!JWTUtil.JWTVerify(token,user.getPassword()))
        {
            Cookie cookie=new Cookie("token","");
            cookie.setMaxAge(0);
            cookie.setPath(contextPath);
            httpServletResponse.addCookie(cookie);
            PrintWriter out=httpServletResponse.getWriter();
            resultDTO.setMsg("登陆过期");
            out.println(resultDTO);
            out.flush();
            out.close();
            return false;
        }
        return true;
    }

    private boolean ispermitUrl(String Aurl){
        for (String url:permitUrlList) {
            if(url.endsWith("/**")){
                String remove=url.replace("/**","");
                if(Aurl.startsWith(remove)){
                    return true;
                }
            }else if(url.equals(Aurl)){
                return true;
            }
        }
        return false;
    }
}
